<template>
  <div>
    <el-upload
      action=""
      :limit="1"
      accept=".xlsx, .xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
      :show-file-list="true"
      :before-upload="beforeUpload"
      :http-request="handleMany"
      :on-change="handleChange"
      :before-remove="beforeRemove"
    >
      <el-button type="success">导入表格</el-button>
    </el-upload>
    <el-button type="danger" @click="exportData">导出表格</el-button>
  </div>
  <div class="show-box">
    <div v-if="sheetData.length !== 0">
      <h3>表格数据</h3>
      <h5>共有数据量: {{ sheetData.length }}条</h5>
      <div v-for="(sheet, index) in Raw_Data" :key="index" class="table-ranks">
        <span v-for="(e, index) in sheet" :key="index" class="table-content">
          {{ e }}
        </span>
      </div>
    </div>
    <div v-if="hexData.length !== 0">
      <h3>转换后的数据展示</h3>
      <div v-for="(sheet, index) in hexData" :key="index" class="table-ranks">
        <span v-for="(e, index) in sheet" :key="index" class="table-content">{{
          e
        }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import * as XLSX from "xlsx";
import { ElMessage } from "element-plus";
import { saveAs } from "file-saver";

const beforeUpload = (e) => {
  //   console.log(e);
  if (
    e.type !==
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" &&
    e.type !== "application/vnd.ms-excel"
  ) {
    alert("请选择有效的Excel文件");
    return false;
  }
  return true;
};
const file_name = ref("");
const sheetData = ref([]);
const handleMany = async (e) => {
  let file = e.file;
  console.log("el-upload==>", file);
  // 获取文件名称
  file_name.value = file.name.split(".")[0];
  console.log("上传的文件名称 ==> ", file_name.value);
  let reader = new FileReader();
  reader.onload = (e) => {
    let data = e.target.result;
    let workbook = XLSX.read(data, { type: "binary" });
    let worksheet = workbook.Sheets[workbook.SheetNames[0]];
    // console.log("解析后的数据==>", worksheet);
    let json = XLSX.utils.sheet_to_json(worksheet);
    // console.log(json);
    sheetData.value = json;
    // 清空原本的数据
    Raw_Data.value = [];
    analyzeSheetData(json);
  };
  reader.readAsBinaryString(file);
};

const handleChange = (e) => {
  // console.log(e.raw);
};

// 需要处理的数据
const Raw_Data = ref([]);
// 处理解析出来的表格数据，并展示在页面上
const analyzeSheetData = (e) => {
  // console.log("开始处理数据==>", e);
  Raw_Data.value.push(Object.keys(e[0]));
  e.map((item) => {
    Raw_Data.value.push(Object.values(item));
    // console.log(Object.keys(item), Object.values(item));
  });
};

const hexData = ref([]);
const exportData = () => {
  if (sheetData.value.length !== 0) {
    const row_length = Raw_Data.value.length;
    let new_raw = Raw_Data.value.slice(1, row_length);
    new_raw.forEach((row) => {
      // console.log(row);
      const hexRow = row.map((value) => {
        if (typeof value === "string") {
          return value.charCodeAt(0).toString(2); // 将字符串转换为16进制
        } else if (typeof value === "number" || typeof value === "boolean") {
          return value.toString(2); // 将数字和布尔值转换为16进制
        } else {
          return ""; // 其他类型的数据保留为空字符串
        }
        console.log(value);
      });
      hexData.value.push(hexRow);
    });

    // 创建一个Blob对象
    const blob = new Blob([hexData.value], {
      type: "application/octet-stream",
    });
    // 使用FileSaver.js保存Blob对象
    saveAs(blob, `${file_name.value}.bin`);
  } else {
    ElMessage({
      message: "请先导入原始数据",
      type: "warning",
      showClose: true,
      grouping: true,
      duration: 2000,
    });
  }
};

// 移除上传的文件
const beforeRemove = (file) => {
  console.log(file);
};
</script>

<style lang="less">
.table-ranks {
  display: flex;
  .table-content {
    padding: 4px;
    text-align: center;
    min-width: 90px;
  }
}
.show-box {
  // display: flex;
  font-size: 12px;
}
</style>